package cn.yangliu.poi.tools;

import cn.yangliu.comm.tools.DateUtils;
import cn.yangliu.comm.tools.ReflectUtils;
import cn.yangliu.poi.PoiConst;
import cn.yangliu.poi.annotation.ExportDateFormate;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 作者 杨柳
 * 创建时间 2017-07-16 16:13
 */
public interface ExportUtils {

    String DEFUAL_FORMATE = "yyyy-MM-dd HH:mm:ss";


    /**
     * 获取字符串
     *
     * @param value
     * @param field
     * @return
     */
    default String getStringValue(Object value, Field field) {
        String valueString = "";
        if (value == null) {
            return "";
        }
        if (value instanceof Number) {
            valueString += value;
        } else if (value instanceof Date) {
            Date date = (Date) value;
            Annotation annotation = ReflectUtils.getFieldAnnotation(field, ExportDateFormate.class);
            String formate = DEFUAL_FORMATE;
            if (annotation != null) {
                formate = ReflectUtils.getAnnotationValue("value", annotation);
            }
            valueString = DateUtils.date2String(date, formate);
        } else if (value instanceof LocalDateTime) {
            Annotation annotation = ReflectUtils.getFieldAnnotation(field, ExportDateFormate.class);
            String formate = DEFUAL_FORMATE;
            if (annotation != null) {
                formate = ReflectUtils.getAnnotationValue("value", annotation);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formate);
            valueString = ((LocalDateTime) value).format(formatter);

        } else if (value instanceof String) {
            valueString = (String) value;
        } else {
            valueString = value.toString();
        }
        return valueString;
    }

    default void buildExcelDocument(Map<String, Object> model,
                                    Workbook workbook, HttpServletRequest request,
                                    HttpServletResponse response, LinkedHashMap<String, String> mapping) {
        String filename = DateUtils.date2String(new Date(), "yyyyMMddHHmmss");
        Sheet sheet;
        Cell cell;
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");

        List<Object> list = (List<Object>) model.get("data");
        CellStyle contentStyle = workbook.createCellStyle(); //内容样式
        for (int index = 0, maxIndex = (list.size() - 1) / PoiConst.MAX_EXCEL_COUNT + 1; index < maxIndex; index++) {
            sheet = workbook.createSheet("导出数据" + index);
            CellStyle headerStyle = workbook.createCellStyle(); //标题样式
            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
            headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
            Font headerFont = workbook.createFont();    //标题字体
            headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
            headerFont.setFontHeightInPoints((short) 11);
            headerStyle.setFont(headerFont);
            int width = 20;
            short height = 25 * 20;
            sheet.setDefaultColumnWidth(width);

            Set<String> titles = mapping.keySet();
            int title_index = 0;
            Row titleRow = sheet.createRow(0);
            for (String title : titles) { //设置标题
                cell = titleRow.createCell(title_index);
                cell.setCellStyle(headerStyle);
                cell.setCellValue(title);
                title_index++;
            }
            sheet.getRow(0).setHeight(height);
            contentStyle.setAlignment(CellStyle.ALIGN_CENTER);
            int length = index + 1 == maxIndex ? list.size() : (index + 1) * PoiConst.MAX_EXCEL_COUNT;

            for (int i = index * PoiConst.MAX_EXCEL_COUNT, colIndex = 0; i < length; i++, colIndex++) {
                Row row = sheet.createRow(colIndex + 1);
                Object obj = list.get(i);
                Iterator<Map.Entry<String, String>> it = mapping.entrySet().iterator();
                int data_index = 0;
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    String fieldName = entry.getValue();
                    Object value = ReflectUtils.getValueByGetMethod(fieldName, obj);
                    Field field = ReflectUtils.getField(fieldName, obj);
                    String cellValue = getStringValue(value, field);
                    cell = row.createCell(data_index);
                    cell.setCellStyle(contentStyle);
                    cell.setCellValue(cellValue);
                    data_index++;
                }

            }

        }
    }

}
